import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_house_manager/controller/BuildController.dart';
import 'package:flutter_house_manager/utils/CameraDialog.dart';
import 'package:flutter_house_manager/utils/PromptAction.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  const HouseForm({super.key});

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  final Map _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'name': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面
    'idcardBackUrl': '', // 身份证背面
  };

  BuildController buildController = Get.find();

  // 拉起相册
  // 打开项目
  openLibrary(String tag) async {
    // 1. 实例化一个ImagePicker
    ImagePicker picker = ImagePicker();
    XFile? file = await picker.pickImage(source: ImageSource.gallery);
    if (file != null) {
      // PromptAction.showSuccess("选择照片成功");
      // file.path // 路径 web-blob路径-二进制路径
      setState(() {
        _formData[tag] = file.path; // 选择完照片给字段进行赋值
      });
    }
    Navigator.pop(context);
  }

// tag 选择完照片赋值的字段
  Widget _buildAddIdcardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        showCameraDialog(context, onLibrary: () {
          // 拉起相册
          openLibrary(tag);
        });
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Icon(
            Icons.add,
            size: 30,
            color: Color.fromARGB(255, 85, 145, 175),
          ),
          Text(
            info,
            style: const TextStyle(
              color: Color.fromARGB(255, 85, 145, 175),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(children: [
      SizedBox(
        width: MediaQuery.of(context).size.width - 20,
        height: 300,
        child: kIsWeb
            ? Image.network(photoUrl, fit: BoxFit.contain)
            : Image.file(File(photoUrl), fit: BoxFit.contain),
      ),
      Positioned(
        right: 0,
        top: 0,
        child: GestureDetector(
          child: const Icon(Icons.delete, color: Colors.red),
          onTap: () {
            setState(() {
              _formData[tag] = '';
            });
          },
        ),
      )
    ]);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 接收来自getx的数据
    _formData["point"] = buildController.buildInfo['point'];
    _formData["building"] = buildController.buildInfo['build'];
    _formData["room"] = buildController.buildInfo['room'];
  }

  _submit() {
    // 提交数据
    // 检查 小区 楼栋 和房间不能为空
    if ((_formData["point"] as String).isEmpty ||
        (_formData["building"] as String).isEmpty ||
        (_formData["room"] as String).isEmpty) {
      PromptAction.showError("小区楼栋房间信息不能为空");
      return;
    }
    if ((_formData["name"] as String).isEmpty) {
      PromptAction.showError("业主姓名不能为空");
      return;
    }
    if (!RegExp(r'^[\u4e00-\u9fa5]{2,10}').hasMatch(_formData["name"])) {
      PromptAction.showError("业主姓名为2-10个汉字");
      return;
    }
    if ((_formData["mobile"] as String).isEmpty) {
      PromptAction.showError("业主电话不能为空");
      return;
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_formData["mobile"])) {
      PromptAction.showError("业主电话格式不正确");
      return;
    }
    // 检查身份证照片是否上传
    if ((_formData["idcardFrontUrl"] as String).isEmpty ||
        (_formData["idcardBackUrl"] as String).isEmpty) {
      PromptAction.showError("请上传身份证照片");
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<BuildController>(builder: (controller) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('添加房屋信息'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: ListView(
          padding: const EdgeInsets.only(top: 10, bottom: 10),
          children: [
            // 房屋信息
            Container(
              padding: const EdgeInsets.all(10),
              child: const Text(
                '房屋信息',
                style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
              ),
            ),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.only(
                  left: 10, right: 10, top: 15, bottom: 15),
              child: Text(
                  '${controller.buildInfo['point']}${controller.buildInfo['build']}${controller.buildInfo['room']}'),
            ),
            // 业主信息
            Container(
              padding: const EdgeInsets.all(10),
              child: const Text(
                '业主信息',
                style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
              ),
            ),
            // 业主姓名
            Container(
              color: Colors.white,
              padding: const EdgeInsets.only(left: 10, right: 10),
              child: TextField(
                maxLength: 15,
                onChanged: (value) {
                  _formData["name"] = value;
                },
                decoration: const InputDecoration(
                  labelText: '姓名',
                  hintText: '请输入业主姓名',
                  hintStyle: TextStyle(color: Colors.grey),
                  border: InputBorder.none,
                ),
                inputFormatters: [
                  LengthLimitingTextInputFormatter(10),
                ],
              ),
            ),
            // 性别
            Container(
              color: Colors.white,
              padding: const EdgeInsets.only(left: 10, right: 10),
              child: Row(
                children: [
                  const Text(
                    '性别',
                    style: TextStyle(fontSize: 16),
                  ),
                  const SizedBox(width: 20),
                  Radio(
                    value: 1,
                    groupValue: _formData['gender'],
                    onChanged: (value) {
                      setState(() {
                        _formData['gender'] = value ?? '';
                      });
                    },
                  ),
                  const Text('男'),
                  const SizedBox(width: 10),
                  Radio(
                    value: 0,
                    groupValue: _formData['gender'],
                    onChanged: (value) {
                      setState(() {
                        _formData['gender'] = value ?? '';
                      });
                    },
                  ),
                  const Text('女'),
                ],
              ),
            ),
            // 业主手机号
            Container(
              color: Colors.white,
              padding: const EdgeInsets.only(left: 10, right: 10),
              child: TextField(
                keyboardType: TextInputType.phone,
                maxLength: 11,
                onChanged: (value) {
                  _formData["mobile"] = value;
                },
                decoration: const InputDecoration(
                  labelText: '手机号',
                  hintText: '请输入您的手机号',
                  hintStyle: TextStyle(color: Colors.grey),
                  border: InputBorder.none,
                ),
                inputFormatters: [
                  LengthLimitingTextInputFormatter(11),
                ],
              ),
            ),
            // 业主信息
            Container(
              padding: const EdgeInsets.all(10),
              child: const Text(
                '本人身份证照片',
                style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94), fontSize: 16),
              ),
            ),
            Container(
              padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
              child: const Text(
                '请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。',
                style: TextStyle(
                    color: Color.fromARGB(255, 97, 94, 94), fontSize: 12),
              ),
            ),
            // 身份证正面
            Container(
              color: Colors.white,
              height: 320,
              padding: const EdgeInsets.all(10),
              child: _formData['idcardFrontUrl'] == ''
                  ? _buildAddIdcardPhoto('idcardFrontUrl', '上传人像面照片')
                  : _buildIdcardPhoto(
                      'idcardFrontUrl',
                      _formData['idcardFrontUrl'],
                    ),
            ),
            const SizedBox(height: 20),
            // 身份证反面
            Container(
              color: Colors.white,
              height: 320,
              padding: const EdgeInsets.all(10),
              child: _formData['idcardBackUrl'] == ''
                  ? _buildAddIdcardPhoto('idcardBackUrl', '上传国徽面照片')
                  : _buildIdcardPhoto(
                      'idcardBackUrl',
                      _formData['idcardBackUrl'],
                    ),
            ),
            const SizedBox(height: 20),
            // 提交审核
            Container(
              padding: const EdgeInsets.all(10),
              child: ElevatedButton(
                onPressed: () {
                  _submit();
                },
                child: const Column(
                  children: [
                    SizedBox(height: 8),
                    Icon(Icons.exit_to_app),
                    Text('提交审核'),
                    SizedBox(height: 8)
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }
}
